import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/models/review.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/page/community/content_data_holder.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class DetailContentPage extends StatefulWidget {
  const DetailContentPage({super.key});

  @override
  State<DetailContentPage> createState() => _DetailContentPageState();
}

class _DetailContentPageState extends State<DetailContentPage> {
  final UserRepository _userRepository = UserRepository();
  final TextEditingController _reviewController = TextEditingController();

  Content? _currentContent;
  User? _contentAuthor;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadContentData();
    _loadReviews();
  }

  @override
  void dispose() {
    _reviewController.dispose();
    super.dispose();
  }

  // 加载内容数据
  Future<void> _loadContentData() async {
    final content = ContentDataHolder.currentContent;
    if (content == null) {
      setState(() {
        _isLoading = false;
      });
      return;
    }

    try {
      final author = await _userRepository.getUserById(content.userId);

      if (mounted) {
        setState(() {
          _currentContent = content;
          _contentAuthor = author;
          _isLoading = false;
        });
      }
    } catch (e) {
      print('Error loading content data: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 加载评论数据
  void _loadReviews() {
    final content = ContentDataHolder.currentContent;
    if (content?.id != null) {
      context.read<AwakBloc>().add(FetchReviewsByContentIdEvent(content!.id!));
    }
  }

  // 发送评论
  void _sendReview() {
    if (_reviewController.text.trim().isEmpty || _currentContent == null) {
      return;
    }

    final review = Review(
      content: _reviewController.text.trim(),
      userId: 1, // 假设当前用户ID为1
      contentId: _currentContent!.id!,
      createdAt: DateTime.now(),
    );

    context.read<AwakBloc>().add(AddReviewEvent(review));
    _reviewController.clear();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (_currentContent == null) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Content not found'),
              ElevatedButton(
                onPressed: () => Beamer.of(context).beamBack(),
                child: Text('Go Back'),
              ),
            ],
          ),
        ),
      );
    }
    // 触发获取评论的事件
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<AwakBloc>().add(FetchReviewsByContentIdEvent(_currentContent!.id!));
    });

    return Scaffold(
        body: Stack(
          children: [
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [Color(0xFFD7F349), Color(0xFFFFFABA)],
                ),
              ),
              child: Column(
                children: [
                  SizedBox(height: 40.h),
                  // 顶部导航栏
                  Padding(
                    padding: EdgeInsets.all(16.w),
                    child: Row(
                      children: [
                        GestureDetector(
                          onTap: () {
                            Beamer.of(context).beamBack();
                          },
                          child: Icon(AwakSvg.back),
                        ),
                        Expanded(
                          child: Center(
                            child: Text('DETAILS', style: AwakText.titleStyle),
                          ),
                        ),
                        SizedBox(width: 20.w),
                      ],
                    ),
                  ),
                  SizedBox(height: 10.h),
                  // 内容区域
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          // 用户信息和内容
                          _buildContentSection(),
                          SizedBox(height: 30.h),
                          // 评论区域
                          _buildReviewsSection(),
                          SizedBox(height: 100.h), // 为底部输入框留空间
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 底部发送框
            _buildBottomInputSection(),
          ],
        ),
      );
  }

  // 构建内容区域
  Widget _buildContentSection() {
    final authorName = _contentAuthor?.nickname ?? _contentAuthor?.username ?? 'Unknown User';
    final authorAvatar = _contentAuthor?.avatar ?? AwakImages.avatar;
    final authorSignature = _contentAuthor?.signature ?? 'No signature';

    return Container(
      decoration: BoxDecoration(color: Colors.transparent),
      child: Column(
        children: [
          // 用户信息行
          Row(
            children: [
              SizedBox(width: 16.w),
              Container(
                width: 60.w,
                height: 60.h,
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  border: Border.all(color: Colors.black, width: 1.w),
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: AssetImage(authorAvatar),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(width: 10.w),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(authorName, style: AwakText.body16Style),
                  Text(
                    authorSignature,
                    style: AwakText.body14Style.copyWith(
                      color: Colors.grey,
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
              Spacer(),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.h),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: Row(
                  children: [
                    Icon(AwakSvg.report, size: 20.w),
                    SizedBox(width: 6.w),
                    Text(
                      'Issue',
                      style: AwakText.body14Style.copyWith(
                        color: Colors.black,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(width: 16.w),
            ],
          ),
          SizedBox(height: 10.h),
          // 内容图片
          Container(
            width: 370.w,
            height: 300.h,
            margin: EdgeInsets.only(top: 10.h, bottom: 10.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12.r),
              image: DecorationImage(
                image: AssetImage(_currentContent!.picture),
                fit: BoxFit.cover,
              ),
            ),
            clipBehavior: Clip.hardEdge,
          ),
          SizedBox(height: 10.h),
          // 内容描述
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Text(
              _currentContent!.description,
              style: AwakText.body16Style.copyWith(
                fontWeight: FontWeight.w500,
                height: 1.5,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建评论区域
  Widget _buildReviewsSection() {
    return BlocBuilder<AwakBloc, AwakState>(
      buildWhen: (previous, current) {
        // 只在评论相关的状态变化时重建
        return current is ReviewLoading ||
               current is ReviewsLoaded ||
               current is ReviewFailure ||
               current is ReviewSuccess;
      },
      builder: (context, state) {
        if (state is ReviewLoading) {
          return Center(child: CircularProgressIndicator());
        }

        if (state is ReviewFailure) {
          return Center(
            child: Text(
              'Error loading reviews: ${state.message}',
              style: AwakText.body14Style.copyWith(color: Colors.red),
            ),
          );
        }

        if (state is ReviewsLoaded) {
          return Column(
            children: [
              // 评论数量标题
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                child: Row(
                  children: [
                    Text(
                      '${state.reviews.length} Comments In Total',
                      style: TextStyle(
                        fontWeight: FontWeight.w500,
                        fontSize: 16.sp,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 20.h),
              // 评论列表
              ...state.reviews.map((review) => _buildReviewItem(review)),
            ],
          );
        }

        return SizedBox.shrink();
      },
    );
  }

  // 构建单个评论项
  Widget _buildReviewItem(Review review) {
    return FutureBuilder<User?>(
      future: _userRepository.getUserById(review.userId),
      builder: (context, snapshot) {
        final user = snapshot.data;
        final userName = user?.nickname ?? user?.username ?? 'Unknown User';
        final userAvatar = user?.avatar ?? AwakImages.avatar;
        final userSignature = user?.signature ?? 'No signature';

        return Container(
          margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 20.h),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CircleAvatar(
                radius: 20.w,
                backgroundImage: AssetImage(userAvatar),
              ),
              SizedBox(width: 10.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 2.h),
                    Text(userName, style: AwakText.body16Style),
                    Text(
                      userSignature,
                      style: AwakText.body14Style.copyWith(
                        color: Colors.black.withValues(alpha: 0.6),
                        fontWeight: FontWeight.w400,
                        fontSize: 12.sp,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      review.content,
                      style: AwakText.body16Style.copyWith(
                        fontWeight: FontWeight.w600,
                        height: 1.5,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(width: 8.w),
              Icon(AwakSvg.report, size: 22.w),
            ],
          ),
        );
      },
    );
  }

  // 构建底部输入区域
  Widget _buildBottomInputSection() {
    return Positioned(
      left: 0,
      right: 0,
      bottom: 40.h,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        child: Row(
          children: [
            Expanded(
              child: Container(
                height: 44.h,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.r),
                  border: Border.all(color: Colors.black, width: 2.w),
                ),
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 2.h),
                child: TextField(
                  controller: _reviewController,
                  decoration: InputDecoration(
                    hintText: 'Send A Message',
                    hintStyle: AwakText.body16Style.copyWith(
                      color: const Color(0xFFCDCDCD),
                      fontWeight: FontWeight.w600,
                    ),
                    border: InputBorder.none,
                  ),
                ),
              ),
            ),
            SizedBox(width: 8.w),
            GestureDetector(
              onTap: _sendReview,
              child: Container(
                height: 44.h,
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                decoration: BoxDecoration(
                  color: Colors.black,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Center(
                  child: Text(
                    'Send',
                    style: TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.sp,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
